﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.Security;
using CultuRAM.DAL;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using CultuRAM.Filters;
using CultuRAM.Models;
using PagedList;
using IsolationLevel = System.Transactions.IsolationLevel;

namespace CultuRAM.Controllers
{

    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {

        CultuRAMContext _db = new CultuRAMContext();
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();
        private ValidateLogin vLogin = new ValidateLogin();
        private static int _page;


        //
        // GET: /Account/Default

        [AllowAnonymous]
        public ActionResult _Default(string returnUrl)
        {
            return PartialView();
        }
        
        
        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // GET: /Account/UserManager
        public ActionResult UserManager(int page = 0)
        {
            if (!Request.HttpMethod.Equals("GET"))
            {
                page = 1;
            }

            const int pageSize = 11;
            int pageNumber;

            if (_page == 0)
            {
                pageNumber = page == 0 ? 1 : page;
            }
            else
            {
                pageNumber = _page;
            }
            _page = 0;
            
            var model = new RegisterModel();

            var entityId = vLogin.GetEntityUser();

            model.UsersProfile = vLogin.ValUserRole("Administrador do Sistema") ?
                _db.UserProfiles.ToList().ToPagedList(pageNumber, pageSize) : 
                _db.UserProfiles.ToList().Where(f => f.EntityId == entityId).ToPagedList(pageNumber, pageSize);
            

            model.RolesList = new SelectList(_db.Roles.ToList(), "RoleName", "RoleName");

            return View(model);
            //return View(model.ToPagedList(pageNumber, pageSize));
            //return PartialView("_ListUserRoles", model1.ToPagedList(pageNumber, pageSize));
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var userRegistered = _unitOfWork.UserProfileRepository.Get().FirstOrDefault(f => f.Email == model.Email);
           
                if (userRegistered != null)
                {
                    var firstOrDefault = _unitOfWork.AccResquestRepository.Get().FirstOrDefault(f => f.EntityId == userRegistered.EntityId);

                    if (firstOrDefault != null)
                    {
                        var stateAccReq = firstOrDefault.AccStateId;
                        //Verify if state the AccRequest is "Aceite"
                        if (stateAccReq != 3)
                        {
                            Session["MsgError"] =
                                "O seu pedido de adesão ainda não foi Aceite. Tente mais tarde. Obrigado!";
                            return RedirectToAction("Auth", "Home");
                        }
                    }
                    else
                    {
                        Session["MsgError"] = "Ocorreu um erro durante autenticação. Tente novamente!";
                        return RedirectToAction("Auth", "Home");
                    }

                    if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
                    {

                        return RedirectToLocal(returnUrl);
                        //return RedirectToAction("Index","Home");
                    }
                }
                else
                {
                    Session["MsgError"] = "O email introduzido não se encontra registado na nossa base de dados.";
                    return RedirectToAction("Auth", "Home");
                }
    
            }
           

            //const string msgError = "Email e/ou palavra-passe inválido(s).";
            Session["MsgError"] = "Email e/ou palavra-passe inválido(s).";

            return RedirectToAction("Auth", "Home");

        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();
            Session["UserName"] = "";
            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOff1()
        {
            WebSecurity.Logout();
            Session["UserName"] = "";
            return RedirectToAction("Index", "Home");
        }

        public ActionResult ListUsersPv(int page = 0)
        {
            if (!Request.HttpMethod.Equals("GET"))
            {
                page = 1;
            }

            const int pageSize = 11;
            int pageNumber;

            if (_page == 0)
            {
                pageNumber = page == 0 ? 1 : page;
            }
            else
            {
                pageNumber = _page;
            }
            _page = 0;

            var entityId = vLogin.GetEntityUser();

            RegisterModel model;

            if (vLogin.ValUserRole("Administrador do Sistema") || vLogin.ValUserRole("Utilizador do Sistema"))
            {
                model = new RegisterModel
                    {
                        UsersProfile = _db.UserProfiles.ToList().ToPagedList(pageNumber, pageSize)
                    };
            }
            else
            {
                model = new RegisterModel
                {
                    UsersProfile = _db.UserProfiles.ToList().Where(f => f.EntityId == entityId).ToPagedList(pageNumber, pageSize)
                };
            }
            

            return PartialView("_ListUsers", model);
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        //[Authorize(Roles = "Adminisrador do Sistema")] 
        public ActionResult Register()
        {
            if (vLogin.ValUserRole("Administrador do Sistema") || vLogin.ValUserRole("Administrador"))
            {
                var registerModel = new RegisterModel
                {
                    RolesList = new SelectList(_db.Roles.ToList(), "RoleName", "RoleName"),
                    EntitiesList = new SelectList(_unitOfWork.EntityRepository.Get().OrderBy(o => o.Name).ToList(), "EntityId", "Name")
                };

                return PartialView("Register", registerModel);             
            }

            ViewBag.MsgError = new MvcHtmlString("Não tem autorização para efetuar está operação!");
            return PartialView("_Default");
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.Email, model.Password, new { UserName = model.UserName, EntityId = model.EntityId }, false);
                    Roles.AddUserToRole(model.Email, model.RoleName);
                    //WebSecurity.Login(model.Email, model.Password);

                    _db.SaveChanges();

                    //return RedirectToAction("UserManager", "Account");
                    // model = new RegisterModel();
                    //model.RolesList = new SelectList(_db.Roles.ToList(), "RoleName", "RoleName");

                    ViewBag.MsgWarning = new MvcHtmlString("O utilizador foi registado com sucesso!");
                    return PartialView("_Default");

                }
                catch (MembershipCreateUserException)
                {
                    ViewBag.MsgError = new MvcHtmlString("Ocorreu um erro ao registar o utilizador!");
                    return PartialView("_Default");
                    //ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form

            model.RolesList = new SelectList(_db.Roles.ToList(), "RoleName", "RoleName");
            model.EntitiesList = new SelectList(_unitOfWork.EntityRepository.Get().OrderBy(o => o.Name).ToList(), "EntityId", "Name");

            return PartialView("Register", model);
        }

        //
        // GET: /Account/Edit/1

        public ActionResult Edit(int id = 0, int m = 0)
        {
            if (id == 0)
            {
                ViewBag.MsgWarning = new MvcHtmlString("<b>ATENÇÃO:</b><br> Selecione o utilizador que pretende editar, clicando numa das linhas da tabela!");
                return PartialView("_Default");
            }

            if (vLogin.ValUserRole("Administrador do Sistema") || vLogin.ValUserRole("Administrador"))
            {
                var up = _db.UserProfiles.Find(id);
                var ms = _db.Memberships.Find(id);

                var roleName = Roles.GetRolesForUser(up.Email);
                var roleId = 0;

                foreach (var r in _db.Roles)
                {
                    if (r.RoleName.Equals(roleName[0]))
                    {
                        roleId = r.RoleId;
                    }
                }
                var role = _db.UserInRoles.Find(id, roleId);

                var rm = new RegisterModel();

                rm.UserName = up.UserName;
                rm.Email = up.Email;
                rm.Password = ms.Password;
                rm.RoleName = role.Roles.RoleName;
                rm.EntityId = up.EntityId;

                rm.RolesList = vLogin.ValUserRole("Administrador do Sistema") ? 
                    new SelectList(_db.Roles.ToList(), "RoleName", "RoleName", roleName[0]) : 
                    new SelectList(_db.Roles.Where(f => f.RoleId >= 3).ToList(), "RoleName", "RoleName", roleName[0]);
            
                rm.EntitiesList = new SelectList(_unitOfWork.EntityRepository.Get().OrderBy(o => o.Name).ToList(), "EntityId", "Name", up.EntityId);

                ViewBag.m = m;

                if (m == 1)
                {
                    return View("Edit", rm);
                }

                return PartialView("Edit", rm);
            }

            ViewBag.MsgError = new MvcHtmlString("Não tem autorização para efetuar está operação!");
            return PartialView("_Default");

        }


        //
        // POST: /Account/Edit

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(RegisterModel model, int id = 0, int m = 0)
        {
            model.RolesList = new SelectList(_db.Roles.ToList(), "RoleName", "RoleName");
            model.EntitiesList = new SelectList(_unitOfWork.EntityRepository.Get().OrderBy(o => o.Name).ToList(), "EntityId", "Name");

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    var roleId = 0;
                    var roleName = Roles.GetRolesForUser(model.Email);
                    foreach (var r in _db.Roles)
                    {
                        if (r.RoleName.Equals(roleName[0]))
                        {
                            roleId = r.RoleId;
                        }
                    }
                    var wur = _db.UserInRoles.Find(id, roleId);
                    var wms = _db.Memberships.Find(id);

                    var wup = _db.UserProfiles.Find(id);
                    wup.UserName = model.UserName;
                    wup.EntityId = model.EntityId;

                    _db.UserInRoles.Remove(wur);
                    _db.Memberships.Remove(wms);
                    _db.Entry(wup).State = EntityState.Modified;
                    _db.SaveChanges();

                    WebSecurity.CreateAccount(model.Email, model.Password);
                    Roles.AddUserToRole(model.Email, model.RoleName);

                    //model.RolesList = new SelectList(_db.Roles.ToList(), "RoleName", "RoleName", model.RoleName);


                    if (m == 1)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    //return RedirectToAction("UserManager", "Account");
                    ViewBag.MsgSuccess = new MvcHtmlString("O dados do utilizador foram alterados com sucesso!");
                    return PartialView("_Default");


                    //return PartialView("Create");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form

            if (m == 1)
            {
                return View("Edit", model);
            }
            return PartialView("Edit", model);
        }

        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "A sua palavra-passe foi alterada."
                : message == ManageMessageId.SetPasswordSuccess ? "A sua palavra-passe foi definida."
                : message == ManageMessageId.RemoveLoginSuccess ? "O login externo foi removido."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "A palavra-passe atual está incorreta ou a nova palavra-passe é inválida.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }




        // GET: /Account/Delete/

        public ActionResult Delete(int id = 0)
        {
            if (id == 0)
            {
                ViewBag.MsgWarning = new MvcHtmlString("<b>ATENÇÃO:</b><br> Selecione o utilizador que pretende eliminar, clicando numa das linhas da tabela!");
                return PartialView("_Default");
            }
            
            if (vLogin.ValUserRole("Administrador do Sistema") || vLogin.ValUserRole("Administrador"))
            {

                var model = _db.UserProfiles.Find(id);

                return PartialView("_Delete", model);
            }
            
            ViewBag.MsgError = new MvcHtmlString("Não tem autorização para efetuar está operação!");
            return PartialView("_Default");

            //return PartialView("UserManager");
        }

        // POST: /Account/Delete/

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult ConfirmDelete(int id = 0)
        {
            

            var webpagesUsersInRoles = _unitOfWork.UserInRolesRepository.Get(filter: x => x.UserId == id).FirstOrDefault();
            if (webpagesUsersInRoles != null)
            {
                var idR = webpagesUsersInRoles.RoleId;

                try
                {
                    webpages_UsersInRoles wur = _db.UserInRoles.Find(id, idR);
                    _db.UserInRoles.Remove(wur);

                    webpages_Membership ms = _db.Memberships.Find(id);
                    _db.Memberships.Remove(ms);

                    UserProfile up = _db.UserProfiles.Find(id);
                    _db.UserProfiles.Remove(up);

                    _db.SaveChanges();

                    ViewBag.MsgInfo = new MvcHtmlString("O utilizador \"" + up.UserName + "\" foi eliminado com sucesso.");
                    return PartialView("_Default");
                }
                catch (System.Data.DataException)
                {
                    UserProfile up = _db.UserProfiles.Find(id);
                    ViewBag.MsgError = new MvcHtmlString("Ocorreu um erro ao eliminar o utilizador \"" + up.UserName + "\".");
                    return PartialView("_Default");

                    //Log the error (add a variable name after DataException)
                    //return RedirectToAction("Delete",
                    //                        new System.Web.Routing.RouteValueDictionary {
                    //                            { "id0", id },
                    //                            { "saveChangesError", true } 
                    //                        });
                }
            }

            //return RedirectToAction("UserManager");

            ViewBag.MsgError = new MvcHtmlString("Ocorreu um erro ao eliminar o utilizador.");

            return PartialView("_Default");
        }


        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "Este nome de utilizador já existe. Por favor insira um nome de utilizador diferente.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region Helpers

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                //return RedirectToAction("Index", "Home");
                return RedirectToAction("Dashboard", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        #endregion
    }
}
